/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package com.liu.modules.business.service.impl;

import com.liu.exception.BadRequestException;
import com.liu.modules.business.domain.EjlCusUserInfo;
import com.liu.utils.*;
import lombok.RequiredArgsConstructor;
import com.liu.modules.business.repository.EjlCusUserInfoRepository;
import com.liu.modules.business.service.EjlCusUserInfoService;
import com.liu.modules.business.service.dto.EjlCusUserInfoDto;
import com.liu.modules.business.service.dto.EjlCusUserInfoQueryCriteria;
import com.liu.modules.business.service.mapstruct.EjlCusUserInfoMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import cn.hutool.core.util.IdUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.util.*;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import javax.servlet.http.HttpServletResponse;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author Liu
* @date 2022-07-03
**/
@Service
@RequiredArgsConstructor
public class EjlCusUserInfoServiceImpl implements EjlCusUserInfoService {

    private final EjlCusUserInfoRepository ejlCusUserInfoRepository;
    private final EjlCusUserInfoMapper ejlCusUserInfoMapper;
    private final RedisUtils redisUtils;

    @Override
    public Map<String,Object> queryAll(EjlCusUserInfoQueryCriteria criteria, Pageable pageable){
        Page<EjlCusUserInfo> page = ejlCusUserInfoRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(ejlCusUserInfoMapper::toDto));
    }

    @Override
    public List<EjlCusUserInfoDto> queryAll(EjlCusUserInfoQueryCriteria criteria){
        return ejlCusUserInfoMapper.toDto(ejlCusUserInfoRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public EjlCusUserInfoDto findById(String userId) {
        EjlCusUserInfo ejlCusUserInfo = ejlCusUserInfoRepository.findById(userId).orElseGet(EjlCusUserInfo::new);
        ValidationUtil.isNull(ejlCusUserInfo.getUserId(),"EjlCusUserInfo","userId",userId);
        return ejlCusUserInfoMapper.toDto(ejlCusUserInfo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public EjlCusUserInfoDto create(EjlCusUserInfo resources) {
        resources.setUserId(IdUtil.simpleUUID()); 
        return ejlCusUserInfoMapper.toDto(ejlCusUserInfoRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(EjlCusUserInfo resources) {
        EjlCusUserInfo ejlCusUserInfo = ejlCusUserInfoRepository.findById(resources.getUserId()).orElseGet(EjlCusUserInfo::new);
        ValidationUtil.isNull( ejlCusUserInfo.getUserId(),"EjlCusUserInfo","id",resources.getUserId());
        ejlCusUserInfo.copy(resources);
        ejlCusUserInfoRepository.save(ejlCusUserInfo);
    }

    @Override
    public void deleteAll(String[] ids) {
        for (String userId : ids) {
            ejlCusUserInfoRepository.deleteById(userId);
        }
    }

    @Override
    public void download(List<EjlCusUserInfoDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (EjlCusUserInfoDto ejlCusUserInfo : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("用户名", ejlCusUserInfo.getUsename());
            map.put("用户手机", ejlCusUserInfo.getUserPhone());
            map.put("用户邮箱", ejlCusUserInfo.getUserEmail());
            map.put("用户密码", ejlCusUserInfo.getUserPassword());
            map.put("用户注册时间", ejlCusUserInfo.getUserRegisterDate());
            map.put("用户标识", ejlCusUserInfo.getUserFlag());
            map.put("用户最后登录时间", ejlCusUserInfo.getUserLastLoginDate());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public EjlCusUserInfoDto register(Map<String, Object> userMap) {
        EjlCusUserInfo ejlCusUserInfo = new EjlCusUserInfo();
        ejlCusUserInfo.setUsename((String)userMap.get("usename"));
        ejlCusUserInfo.setUserPassword((String)userMap.get("password"));
        ejlCusUserInfo.setUserEmail((String)userMap.get("userEmail"));
        ejlCusUserInfo.setUserPhone((String)userMap.get("userPhone"));
        ejlCusUserInfo.setUserFlag((String)userMap.get("userFlag"));
        ejlCusUserInfo.setUserRegisterDate(DateUtil.localDateTimeFormat(DateUtil.toLocalDateTime(new Date()),"yyyyMMdd"));
        String phoneCode = (String)userMap.get("phoneCode");
        String uuid = (String)userMap.get("uuid");
        String  code = (String)redisUtils.get(uuid);
        if (StringUtils.isBlank(code)) {
            throw new BadRequestException("验证码不存在或已过期");
        }
        if (StringUtils.isBlank(phoneCode) || !code.equalsIgnoreCase(phoneCode)) {
            throw new BadRequestException("验证码错误");
        }
        return create(ejlCusUserInfo);
    }
}